#! /usr/bin/env python3
import pymysql
import re
import sys

try:
    sys.stdout = open('/tmp/exp_group.json','w')
    conn=pymysql.connect(host='slurm08.ihep.ac.cn',user='htc_query',passwd='read_htc123',db='htc_info',port=3306)
    cur=conn.cursor()
    cur.execute('select experiment, main_group_name from experiment_quota')
    allExps=cur.fetchall()
    countExp=len(allExps)
    print("{")
    j=1
    for eachExp in allExps:
        print('\t"'+eachExp[0]+'":{')
        if (eachExp[1]):
            print('\t\t"main_group":"'+eachExp[1]+'",')
        else:
            print('\t\t"main_group":"",')
        print('\t\t"sub_groups":', end=' ')
        sql='select group_name from group_quota where experiment="'+ eachExp[0] +'"'
        cur.execute(sql)
        allGroups=cur.fetchall()
        countGrp=len(allGroups)
        if countGrp<1:
            print("[]")
            print("\t},")
        else:
            i=1
            print('[', end=' ')
            for eachGroup in allGroups:
                print('"'+eachGroup[0]+'"', end=' ')
                if (i<countGrp):
                    i=i+1
                    print(",", end=' ')
                else:
                    print("]")
                    if (j<countExp):
                        print('\t},')
                    else:
                        print('\t}')
        j=j+1
    print('}')
    cur.close()
    conn.close()
    sys.stdout.close()
except:
#    print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    sys.exit(1)
